//
//  RespEntity.swift
//  ProjectApp
//
//  Created by jack on 2021/1/8.
//

import Foundation
class RespEntity<T: Codable> {
    var code: Int?
    var msg: String?
    var data: T?
    
    init(dic: [String : Any]) {
        if let value = dic["code"] as? Int {
            self.code = value
        }

        if let value = dic["msg"] as? String {
            self.msg = value
        }
        
        if let tempJson: Any = dic["data"] {
            if !(tempJson is NSNull) { // 防止data为null
                if tempJson is String  { // T -> String
                    self.data = tempJson as? T
                } else if tempJson is Double { // T -> Double, data为数字时，T不能是Float，使用Double通用
                    self.data = tempJson as? T
                } else {
                    if let tempData: Data = try? JSONSerialization.data(withJSONObject: tempJson, options: JSONSerialization.WritingOptions.prettyPrinted){
                        if let model: T = try? JSONDecoder().decode(T.self, from: tempData) {
                            self.data = model
                        }
                    }
                }
            }
        }
    }
    
    var suc: Bool {
        var flag = false
        if let c = self.code, c == 10000 {
            flag = true
        }
        return flag
    }
}
